from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import sqlite3
import json
import feedparser
from datetime import datetime
from typing import List, Dict, Any
from pathlib import Path

app = FastAPI(title="专业领域资讯服务", version="1.0.0")

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 数据库路径
DB_PATH = "data/news.db"

def init_db():
    """初始化数据库"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # 创建文章表
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS articles (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT,
            summary TEXT,
            url TEXT,
            source TEXT NOT NULL,
            category TEXT,
            keywords TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)
    
    # 创建关键词表
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS keywords (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            keyword TEXT UNIQUE NOT NULL,
            category TEXT,
            is_active INTEGER DEFAULT 1,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)
    
    # 插入默认关键词
    default_keywords = [
        ("人工智能", "ai"),
        ("机器学习", "ai"),
        ("深度学习", "ai"),
        ("区块链", "tech"),
        ("云计算", "tech")
    ]
    
    for keyword, category in default_keywords:
        cursor.execute("""
            INSERT OR IGNORE INTO keywords (keyword, category)
            VALUES (?, ?)
        """, (keyword, category))
    
    conn.commit()
    conn.close()

@app.on_event("startup")
async def startup_event():
    """启动时初始化"""
    print("🚀 启动专业领域资讯服务...")
    init_db()

@app.get("/")
async def root():
    return {"message": "专业领域资讯服务", "version": "1.0.0"}

@app.get("/api/keywords")
async def get_keywords():
    """获取关键词列表"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM keywords WHERE is_active = 1")
    keywords = []
    for row in cursor.fetchall():
        keywords.append({
            "id": row[0],
            "keyword": row[1],
            "category": row[2],
            "is_active": bool(row[3]),
            "created_at": row[4]
        })
    conn.close()
    return keywords

@app.post("/api/keywords")
async def add_keyword(keyword: str, category: str = "general"):
    """添加关键词"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    try:
        cursor.execute("""
            INSERT INTO keywords (keyword, category)
            VALUES (?, ?)
        """, (keyword, category))
        conn.commit()
        conn.close()
        return {"message": "关键词添加成功"}
    except sqlite3.IntegrityError:
        conn.close()
        raise HTTPException(status_code=400, detail="关键词已存在")

@app.get("/api/articles")
async def get_articles(limit: int = 50):
    """获取文章列表"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        SELECT * FROM articles 
        ORDER BY created_at DESC 
        LIMIT ?
    """, (limit,))
    articles = []
    for row in cursor.fetchall():
        articles.append({
            "id": row[0],
            "title": row[1],
            "content": row[2],
            "summary": row[3],
            "url": row[4],
            "source": row[5],
            "category": row[6],
            "keywords": json.loads(row[7]) if row[7] else [],
            "created_at": row[8]
        })
    conn.close()
    return articles

@app.post("/api/collect")
async def collect_articles():
    """收集RSS文章"""
    rss_sources = {
        "nature": "https://www.nature.com/rss/current_aw.xml",
        "arxiv_ai": "http://export.arxiv.org/rss/cs.AI",
        "techcrunch": "https://techcrunch.com/feed/"
    }
    
    collected = 0
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    for source_name, url in rss_sources.items():
        try:
            feed = feedparser.parse(url)
            for entry in feed.entries[:10]:
                # 检查是否已存在
                cursor.execute("SELECT COUNT(*) FROM articles WHERE url = ?", (entry.get("link", ""),))
                if cursor.fetchone()[0] == 0:
                    cursor.execute("""
                        INSERT INTO articles (title, content, summary, url, source, category)
                        VALUES (?, ?, ?, ?, ?, ?)
                    """, (
                        entry.get("title", ""),
                        entry.get("summary", ""),
                        entry.get("summary", "")[:500],
                        entry.get("link", ""),
                        source_name,
                        "rss"
                    ))
                    collected += 1
        except Exception as e:
            print(f"获取 {source_name} 失败: {e}")
    
    conn.commit()
    conn.close()
    
    return {"message": f"收集完成，新增 {collected} 篇文章"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
